package org.jfsm.demo.ccounter.timer;

import org.jfsm.core.FSMReplyContext;
import org.jfsm.core.RetSignal;
import org.jfsm.core.SimpleFSM;

public class TimerFSM extends SimpleFSM<TimerContext, TimerRequest, TimerResponse> {

    enum State {
        Null, Init, Run
    }

    @Override
    protected void build(TransitionMap tm) {
        tm.setInitialState(State.Null);

        tm.put(State.Null, in.init, State.Init, ehInit);
        tm.put(State.Init, in.start, State.Run, shStart);
        tm.put(State.Run, in.timeout, State.Init, ehTimeout);
    }

    EH ehInit = new EH() {
        @Override
        public RetSignal handle(TimerContext ctx) {
            ctx.callBack = in;
            return null;
        }
    };

    SH<Long> shStart = new SH<Long>() {
        @Override
        public RetSignal handle(TimerContext ctx, Long msg, FSMReplyContext replyCtx) {
            ctx.replyCtx = replyCtx;
            ctx.start(msg);
            return null;
        }
    };

    EH ehTimeout = new EH() {
        @Override
        public RetSignal handle(TimerContext ctx) {
            out.timeout.dispatch(ctx.replyCtx);
            return null;
        }
    };
}
